from sqlalchemy import Column, String, Integer, ForeignKey, DateTime, Text, Float, Boolean, Table
from sqlalchemy.orm import relationship
from enum import Enum as PyEnum

from app.models.base import Base


class ResourceType(PyEnum):
    HUMAN = "human"  # 人力资源
    MATERIAL = "material"  # 物料资源
    EQUIPMENT = "equipment"  # 设备资源
    FINANCIAL = "financial"  # 财务资源


class ResourceAvailability(PyEnum):
    AVAILABLE = "available"  # 可用
    PARTIALLY_AVAILABLE = "partially_available"  # 部分可用
    UNAVAILABLE = "unavailable"  # 不可用
    SCHEDULED = "scheduled"  # 已排期


# 资源与项目的多对多关联表
resource_project = Table(
    "resource_project",
    Base.metadata,
    Column("resource_id", Integer, ForeignKey("resource.id"), primary_key=True),
    Column("project_id", Integer, ForeignKey("project.id"), primary_key=True),
    Column("allocation_percentage", Float, default=100.0),  # 分配百分比
    Column("start_date", DateTime, nullable=False),  # 开始日期
    Column("end_date", DateTime, nullable=False),  # 结束日期
)


# 资源与任务的多对多关联表
resource_task = Table(
    "resource_task",
    Base.metadata,
    Column("resource_id", Integer, ForeignKey("resource.id"), primary_key=True),
    Column("task_id", Integer, ForeignKey("task.id"), primary_key=True),
    Column("allocation_percentage", Float, default=100.0),  # 分配百分比
    Column("start_date", DateTime, nullable=False),  # 开始日期
    Column("end_date", DateTime, nullable=False),  # 结束日期
)


class Resource(Base):
    """资源模型"""
    name = Column(String(100), nullable=False, index=True)
    description = Column(Text, nullable=True)
    resource_type = Column(String(20), nullable=False)
    availability = Column(String(20), nullable=False, default=ResourceAvailability.AVAILABLE.value)
    cost_rate = Column(Float, nullable=True)  # 成本率（每小时/天）
    max_units = Column(Float, default=1.0)  # 最大可用单位
    skills = Column(Text, nullable=True)  # 技能/特性（对人力资源）
    location = Column(String(100), nullable=True)  # 位置
    is_external = Column(Boolean, default=False)  # 是否外部资源
    
    # 关系
    projects = relationship("Project", secondary=resource_project, back_populates="resources")
    tasks = relationship("Task", secondary=resource_task, back_populates="resources")